let w = [5, 7,2,3,6,8,9];

function TreeNode(val) {
  this.val = val;
  this.left = this.right = null;
}

function getNode(weights){
  weights.sort((a,b) => a.val - b.val);
  let root = new TreeNode(weights[0].val + weights[1].val)
  root.left = weights[0];
  root.right = weights[1];
  
  weights.shift();
  weights.shift();
  if(!weights.length){
    return root;
  }
  weights.push(root);
  return getNode(weights);
}

function Huffman(weights){
  if(!weights.length) return null;
  if(weights.length < 2) return new TreeNode(weights[0]);
  weights = weights.map(num=> new TreeNode(num));

  return getNode(weights);
}

let result = Huffman(w);
console.log(result)